package com.gufe.other.handler;

import com.gufe.constant.MessageConstant;
import com.gufe.exception.*;
import com.gufe.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("捕获到异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /*捕获sql值重复异常*/
    @ExceptionHandler
    public Result sqlException(SQLIntegrityConstraintViolationException ex){
        log.info("捕获到异常{}",ex.getMessage());
        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String s = split[2]+ MessageConstant.ALREADY_EXISTS;
            return Result.error(s);
        }
        else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

    /*空数据异常*/
    @ExceptionHandler
    public Result NullDataException(NullDataException ex){
        log.info("捕获到空数据异常{}",ex.getMessage());
        if(ex.getMessage() == null){
            return Result.error("存在空数据！");
        }
        return Result.error(ex.getMessage());
    }

    /*事务回滚*/
    @ExceptionHandler
    public Result RollBackException(RollBackException ex){
        log.info("捕获到事务回滚{}",ex.getMessage());
        if(ex.getMessage() == null){
            return Result.error("操作失败！");
        }
        return Result.error(ex.getMessage());
    }

    /*登录异常*/
    @ExceptionHandler
    public Result RollBackException(LoginFailedException ex){
        log.info("捕获登录异常{}",ex.getMessage());
        if(ex.getMessage() == null){
            return Result.error("登录失败！");
        }
        return Result.error(ex.getMessage());
    }

    // 导入Excel中空字段异常
    @ExceptionHandler
    public Result handleEmptyField(EmptyFieldException ex) {
        log.info("空字段异常：{}",ex.getMessage());
        return Result.error("字段不能为空");
    }





}
